import axios from 'axios'
import store from '@/store'
import router from '@/router'
import JSONbig from 'json-bigint'
import { Toast } from 'vant'
// 创建axios实例
const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  transformResponse: [function (data) {
    // `transformResponse` 在传递给 then/catch 前，允许修改响应数据
    // JSONbig转换大数字精度丢失问题
    try {
      return JSONbig.parse(data)
    } catch (error) {
      return data
    }
  }]
})
// 请求拦截器
service.interceptors.request.use(config => {
  const { userToken } = store.state
  if (userToken) {
    config.headers.Authorization = `Bearer ${userToken.token}` // 让每个请求携带自定义token 请根据实际情况自行修改
  }
  return config
}, error => {
  Promise.reject(error)
})

// 响应拦截器
service.interceptors.response.use(
  response => {
    return response
  },
  async err => {
    switch (err.response.status) {
      case 400:
        err.message = '不支持的参数(400)'
        break
      case 401: {
        let { userToken } = store.state
        if (!userToken || !userToken.token) {
          return router.replace({
            path: '/login',
            query: {
              // currentRoute：表示当前路由
              redireact: router.currentRoute.fullPath
            }
          })
        }
        let refreshToken = store.state.userToken.refresh_token
        try {
          const { data } = await axios({
            method: 'PUT',
            url: 'http://toutiao-app.itheima.net/v1_0/authorizations',
            headers: {
              Authorization: `Bearer ${refreshToken}`
            }
          })
          userToken.token = data.data.token
          store.commit('SET_TOKEN', userToken)
          // 重新使用我们之间创建的axios实例，用本次错误请求中的配置项,再发一次
          return service(err.config)
        } catch (error) {
          router.replace({
            path: '/login',
            query: {
              // currentRoute：表示当前路由
              redireact: router.currentRoute.fullPath
            }
          })
        }
      }
        break
      case 404:
        err.message = '被访问资源不存在(404)'
        break
      case 500:
        err.message = '服务端内部错误(500)'
        break
    }
    Toast.fail(err.message)
    return Promise.reject(err)
  }
)

export default service
